package com.domor.controller.system;

import com.domor.model.Result;
import com.domor.model.Table;
import com.domor.service.system.DeptService;
import com.domor.service.system.UserService;
import com.domor.utils.CommonUtils;
import com.domor.utils.DigestUtil;
import com.domor.utils.MapUtils;
import com.domor.utils.ParamUtils;
import com.github.pagehelper.Page;
import io.swagger.annotations.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Map;

@RestController
@RequestMapping("user")
@Api(tags = "BookController", description = "用户管理")
public class UserController {

    @Autowired
    private UserService service;
    @Autowired
    private DeptService deptService;

    @PostMapping("/getByName" )
    public Object getByName(HttpServletRequest request, String username) {
        return service.getByName(username);
    }

    @ApiOperation(value="查询用户列表", notes="查询用户列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "name", value = "用户名或真实姓名", required = false, dataType = "String"),
            @ApiImplicitParam(name = "role", value = "用户角色", required = false, dataType = "int")
    })
    @PostMapping("/query")
    public Object query(HttpServletRequest request) {
        Map<String, Object> params = ParamUtils.getParams(request);
        //获取所有子部门的ID
        int dept = MapUtils.getIntValue(params, "dept");
        params.put("ids", deptService.getChildrenDeptId(dept));
        Page page = CommonUtils.startPage(params);
        Table table = new Table(service.query(params), page.getTotal());
        return Result.success(table);
    }

    @PostMapping("/save")
    public Object save(HttpServletRequest request) {
        Map<String, Object> params = ParamUtils.getParams(request);
        int id = MapUtils.getIntValue(params, "id");
        if (id == 0) {
            params.put("password", DigestUtil.md5("123456"));
            service.insert(params);
        } else {
            service.update(params);
        }
        return Result.success();
    }

    @PostMapping("/delete")
    public Object delete(HttpServletRequest request) {
        Map<String, Object> params = ParamUtils.getParams(request);
        service.delete(params);
        return Result.success();
    }

}
